#include <iostream>
#include <sstream>
#include "disc_lib.h"
#include "Profile.h"

using namespace std;


void disc_read_ini(CaenDiscriminator &disc, char * inifile)
{
    int value;

    Profile ini(inifile);

//  if ((dfile = fopen(inifile, "r")) == NULL)
//      printf("ERROR: Error opening ini file for discriminator (%s)\n", inifile);
//  else 

    for (int i = 0; i < disc.GetNChannels(); i++) {
        stringstream chstr;
        chstr << "Channel" << i;
        int  threshold = ini.GetInt("LEVEL", chstr.str().c_str());
        bool enabled   = ini.GetBool("ENABLED", chstr.str().c_str());

        disc.SetThreshold(i, threshold);
        if (enabled)
            disc.EnableChannel(i);
        else
            disc.DisableChannel(i);
    }

    value = ini.GetInt("DEADTIME", "Group1");
    disc.SetDeadTime(0, value);
    value = ini.GetInt("DEADTIME", "Group2");
    disc.SetDeadTime(1, value);

    value = ini.GetInt("PULSEWIDTH", "Group1");
    disc.SetOutputWidth(0, value);
    value = ini.GetInt("PULSEWIDTH", "Group2");
    disc.SetOutputWidth(1, value);
}


void disc_write_ini(CaenDiscriminator &disc, char * inifile)
{
    Profile ini(inifile);

//  if ((dfile = fopen(inifile,"w")) == NULL)
//      printf("ERROR: Error opening ini file for discriminator (%s)\n", inifile);
//  else

    for (int i = 0; i < disc.GetNChannels(); i++) {
        stringstream chstr;
        chstr << "Channel" << i;
        ini.SetInt("LEVEL", chstr.str().c_str(), disc.GetThreshold(i));
        ini.SetBool("ENABLED", chstr.str().c_str(), disc.ChannelEnabled(i));
    }
    ini.SetInt("DEADTIME", "Group1", disc.GetDeadTime(0));
    ini.SetInt("DEADTIME", "Group2", disc.GetDeadTime(1));
    ini.SetInt("PULSEWIDTH", "Group1", disc.GetOutputWidth(0));
    ini.SetInt("PULSEWIDTH", "Group2", disc.GetOutputWidth(1));
}


void disc_show_settings(CaenDiscriminator &disc)
{
    int i;

    cout <<  "channel:       ";
    for (i = 0; i < disc.GetNChannels(); i++) {
        cout.width(4);
        cout << i;
    }
    cout << endl << "threshold:     ";
    
    for (i = 0; i < disc.GetNChannels(); i++) {
        cout.width(4);
        cout << (int) disc.GetThreshold(i);
    }
    cout << endl << "enabl/dis(1/0):";
    for (i = 0; i < disc.GetNChannels(); i++) {
        cout.width(4);
        cout << disc.ChannelEnabled(i);
    }
    cout << endl;
    cout << "dead time   (ch 0- 7) " << (int) disc.GetDeadTime(0) << endl;
    cout << "dead time   (ch 8-15) " << (int) disc.GetDeadTime(1) << endl;
    cout << "pulse width (ch 0- 7) " << (int) disc.GetOutputWidth(0) << endl;
    cout << "pulse width (ch 8-15) " << (int) disc.GetOutputWidth(1) << endl;
}

